<template>
    <div class="roles_wrap">
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 主体内容区域 -->
        <el-card>
            <!-- 添加角色按钮 -->
            <el-button @click="showAddRoleForm" type="primary">添加角色</el-button>
            <el-table :data="rolesList" border style="width: 100%">
                <!-- 角色权限详细 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="[i1 == 0 ? 'bd-top' : '' , 'bd-bottom']" :key="item1.id" v-for="(item1, i1) in scope.row.children">
                            <!-- 一级权限 -->
                            <el-col :span="5">
                                <el-tag @close="removeRolesRights(scope.row, item1.id)" closable>{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级跟三级权限 -->
                            <el-col :span="19">
                                <el-row :class="[i2 == 0 ? '' : 'bd-top']" :key="item2.id" v-for="(item2, i2) in item1.children">
                                    <!-- 二级权限 -->
                                    <el-col :span="8">
                                        <el-tag @close="removeRolesRights(scope.row, item2.id)" closable type="success">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 三级权限 -->
                                    <el-col :span="16">
                                        <el-tag @close="removeRolesRights(scope.row, item3.id)" closable :key="item3.id" v-for="(item3) in item2.children" type="success">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-row>
                            <!-- 编辑 -->
                            <el-col :span="8">
                                <el-button @click="showModifyForm(scope.row)" size="small" type="primary" icon="el-icon-edit">编辑</el-button>
                            </el-col>
                            <!-- 分配 -->
                            <el-col :span="8">
                                <el-button @click="showSetRightsForm(scope.row)" size="small" type="danger" icon="el-icon-user">分配权限</el-button>
                            </el-col>
                            <!-- 删除 -->
                            <el-col :span="8">
                                <el-button @click="removeRoles(scope.row.id)" size="small" type="danger" icon="el-icon-delete">删除</el-button>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 编辑对话框 -->
        <el-dialog @close="clearModifyForm" title="编辑角色" :visible.sync="isShowModifyForm" width="50%">
            <!-- 表单区域 -->
            <el-form :model="modifyForm" :rules="modifyFormRules" ref="modifyFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="modifyForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="modifyForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowModifyForm = false">取 消</el-button>
                <el-button type="primary" @click="submitModifyForm">确 定</el-button>
            </span>
        </el-dialog>
        
        <!-- 分配权限对话框 -->
        <el-dialog @close="clearDefaultsActiveRights" title="分配权限" :visible.sync="isShowSetRightsForm" width="50%">
            <el-tree ref="treeRef" @check-change="treeSelectChange" node-key="id" :default-checked-keys="defaultsActiveRights" :show-checkbox="true" :default-expand-all="true" :data="rightsList" :props="rightsListProps"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowSetRightsForm = false">取 消</el-button>
                <el-button type="primary" @click="submitSetRightsForm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加角色对话框 -->
        <el-dialog @close="clearModifyForm" title="编辑角色" :visible.sync="isShowAddRoleForm" width="50%">
            <!-- 表单区域 -->
            <el-form :model="modifyForm" :rules="modifyFormRules" ref="modifyFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="modifyForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="modifyForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowAddRoleForm = false">取 消</el-button>
                <el-button type="primary" @click="submitAddRoleForm">确 定</el-button>
            </span>
        </el-dialog>
        
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 存储角色列表
            rolesList: [],
            // 显示或隐藏编辑对话框
            isShowModifyForm: false,
            // 编辑表单跟添加表单的参数
            modifyForm: {
                roleName: '',
                roleDesc: ''
            },
            // 编辑表单的验证规则
            modifyFormRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ]
            },
            // 存储被编辑的角色ID
            modifyRoleID: '',
            // 控制分配权限对话框的显示与隐藏
            isShowSetRightsForm: false,
            // 存储权限列表
            rightsList: [],
            // 分配权限的配置
            rightsListProps: {
                label: 'authName',
                children: 'children'
            },
            // 存储默认被选中的权限项
            defaultsActiveRights: [],
            // 存储被选择的权限ID
            activeRightsID: '',
            // 控制添加角色对话框的显示与隐藏
            isShowAddRoleForm: false,
        }
    },
    created() {
        this.getRolesList();
    },
    methods: {
        // 获取角色列表
        async getRolesList() {
            const { data: res } = await this.$http.get('roles');
            if (res.meta.status != 200) return this.$message.error('获取角色列表失败');
            this.rolesList = res.data;
        },
        // 删除角色权限
        async removeRolesRights(roles, rightID) {
            const { data: res } = await this.$http.delete(`roles/${roles.id}/rights/${rightID}`);
            if (res.meta.status != 200) return this.$message.error('删除角色权限失败');
            roles.children = res.data;
        },
        // 显示编辑对话框
        showModifyForm(roleInfo) {
            this.isShowModifyForm = true;
            // 设置被编辑角色的表单默认值
            this.modifyRoleID = roleInfo.id;
            this.modifyForm.roleName = roleInfo.roleName;
            this.modifyForm.roleDesc = roleInfo.roleDesc;
        },
        // 提交编辑表单
        async submitModifyForm() {
            const { data: res } = await this.$http.put(`roles/${this.modifyRoleID}`, this.modifyForm);
            if (res.meta.status != 200) return this.$message.error('编辑角色失败');
            this.$message.success('编辑角色成功');
            this.isShowModifyForm = false;
            this.getRolesList();
        },
        // 显示分配权限对话框
        async showSetRightsForm(role) {
            this.isShowSetRightsForm = true;
            this.modifyRoleID = role.id;
            // 获取权限列表
            const { data: res } = await this.$http.get(`rights/tree`);
            if (res.meta.status != 200) return this.$message.error('获取权限列表失败，请刷新重试');
            this.rightsList = res.data;
            // 获取角色默认存在的权限ID
            this.getRoleRightsID(role, this.defaultsActiveRights);
            
        },
        // 递归获取角色默认存在的权限ID
        getRoleRightsID(node, arr) {
            if (!node.children) {
                return arr.push(node.id);
            }
            node.children.forEach(item => {
                this.getRoleRightsID(item, arr);
            });
        },
        // 关闭分配对话框时，清空角色默认的权限ID数组
        clearDefaultsActiveRights() {
            this.defaultsActiveRights = [];
        },
        // 当权限节点被选中的时候的回调函数，获取被选中的权限ID
        treeSelectChange() {
            var nodeIDArray = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()];
            this.activeRightsID = nodeIDArray.join(',');
        },
        // 提交分配权限表单
        async submitSetRightsForm() {
            let { data: res } = await this.$http.post(`roles/${this.modifyRoleID}/rights`, { rids: this.activeRightsID });
            if (res.meta.status != 200) return this.$message.error('分配角色权限失败');
            this.$message.success('分配角色权限成功');
            this.isShowSetRightsForm = false;
            this.getRolesList();
        },
        // 删除角色
        removeRoles(roleID) {
            this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete(`roles/${roleID}`);
                if (res.meta.status != 200) return this.$message.error('删除角色失败');
                this.$message.success('删除角色成功');
                this.getRolesList();
            }).catch(() => {
                this.$message.info('取消了删除角色操作');
            });
        },
        // 显示添加角色对话框
        showAddRoleForm() {
            this.modifyForm.roleName = '';
            this.modifyForm.roleDesc = '';
            this.isShowAddRoleForm = true;
        },
        // 提交添加角色表单
        async submitAddRoleForm() {
            const { data: res } = await this.$http.post('roles', this.modifyForm);
            if (res.meta.status != 201) return this.$message.error('创建角色失败');
            this.$message.success('创建角色成功');
            this.isShowAddRoleForm = false;
            this.getRolesList();
        },
        // 修改和添加表单对话框，关闭时清空表单的参数
        clearModifyForm() {
            this.$refs.modifyFormRef.resetFields();
        }
    }
}
</script>

<style lang="less" scoped>
.el-row {
    display: flex;
    align-items: center;
}
.el-tag {
    margin: 10px;
}
.bd-top {
    border-top: 1px solid #ccc;
}
.bd-bottom {
    border-bottom: 1px solid #ccc;
}
</style>